﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ScapiItem = global::Sitecore.Data.Items.Item;
using ScapiDatabase = global::Sitecore.Data.Database;
using ScapiLanguage = global::Sitecore.Globalization.Language;
using ScapiFactory = global::Sitecore.Configuration.Factory;
using ScapiId = global::Sitecore.Data.ID;
using ScapiItemManager = global::Sitecore.Data.Managers.ItemManager;
using ScapiVersion = global::Sitecore.Data.Version;
using ScapiSecurityCheck = global::Sitecore.SecurityModel.SecurityCheck;

namespace Pocahontas.Sitecore
{
	static class SitecoreItemUtility
	{
		public static ScapiItem GetItem(SitecoreItemKey key)
		{
			ScapiDatabase scapiDatabase = ScapiFactory.GetDatabase(key.DatabaseName);

			ScapiLanguage scapiLanguage;

			if (ScapiLanguage.TryParse(key.LanguageName, out scapiLanguage))
			{
				ScapiItem scapiItem = ScapiItemManager.Provider.GetItem(new ScapiId(key.Guid), scapiLanguage, ScapiVersion.Latest, scapiDatabase, ScapiSecurityCheck.Enable);

				if (scapiItem != null && scapiItem.Version.Number > 0 && scapiItem.Versions.Count > 0)
				{
					return scapiItem;
				}
			}

			return null;
		}
	}
}
